#include <memory>
#include <iostream>

using std::cout;
using std::endl;
using std::weak_ptr;
using std::shared_ptr;

class Point
{
public:
    Point(int ix, int iy)
    : _ix(ix)
    , _iy(iy)
    {   cout << "Point(int,int)" << endl;   }

    ~Point()
    {   cout << "~Point()" << endl; }

    void print() const
    {   
        cout << "(" << _ix
             << "," << _iy
             << ")" << endl;
    }

private:
    int _ix;
    int _iy;
};

int main()
{
    weak_ptr<Point> wp;
    //语句块
    {
        shared_ptr<Point> sp(new Point(1, 2));
        sp->print();
        cout << "sp's use_count:" << sp.use_count() << endl;

        wp = sp;//将sp赋值给wp之后，引用计数不会加1，
                //但wp知道所托管的对象是否还存活
        cout << "wp'expried:" << wp.expired() << endl << endl;

        //希望通过wp访问资源
        shared_ptr<Point> sp2 = wp.lock();
        if(sp2) {
            cout << "提升成功" << endl;
            sp2->print();
        } else {
            cout <<  "提升失败, 所托管的对象已经被销毁" << endl;
        }
    }
    //语句块之外，对象已经被销毁

    cout << "\n>> 语句块之外了:" << endl;
    cout << "wp'expried:" << wp.expired() << endl << endl;

    shared_ptr<Point> sp2 = wp.lock();
    if(sp2) {
        cout << "提升成功" << endl;
        sp2->print();
    } else {
        cout <<  "提升失败, 所托管的对象已经被销毁" << endl;
    }




    return 0;
}

